package com.westa.smallshop.goodsdetail;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.westa.smallshop.data.GoodsItem;
import com.westa.smallshop.data.source.GoodsItemDataSource;
import com.westa.smallshop.data.source.remote.BaseDataSource;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by cy123 on 2016/9/14.
 */
public class GoodsDetailPresenter implements GoodsDetailContract.Presenter {

    @NonNull
    private final GoodsDetailContract.View mView;

    @NonNull
    private final GoodsItemDataSource mGoodsItemDataSource;

    private int mGoods_id;

    public GoodsDetailPresenter(@NonNull GoodsDetailContract.View cardContractView,
                                @NonNull GoodsItemDataSource dataSource,
                                @NonNull int goods_id) {
        mView = checkNotNull(cardContractView);
        mGoodsItemDataSource = checkNotNull(dataSource);

        mView.setPresenter(this);
        mGoods_id = goods_id;
    }

    @Override
    public void start() {
        requestCard();
    }


    @Override
    public void destroy() {

    }

    @Override
    public void requestCard() {
        mGoodsItemDataSource.getGoodsItem(mGoods_id, new BaseDataSource.LoadCallBack<GoodsItem>() {
            @Override
            public void onLoadDataSuccessful(GoodsItem data) {
                mView.showGoodsInfo(data);
                mView.setRefreshing(false);
            }

            @Override
            public void onLoadDataFailed() {
                mView.setRefreshing(false);
            }
        });

    }

    @Override
    public void addGoodsToCart(int goodsId) {

        mGoodsItemDataSource.addGoodsToCart(goodsId, new BaseDataSource.LoadCallBack<JSONObject>() {
            @Override
            public void onLoadDataSuccessful(JSONObject data) {
                if (mView.isActive()) {
                    if (TextUtils.equals(data.getString("result"), "0")) {
                        mView.showAddToCartSuccessful();
                    } else {
                        mView.showAddToCartFailed();
                    }
                }
            }

            @Override
            public void onLoadDataFailed() {
                mView.showAddToCartFailed();
            }
        });
    }
}
